﻿using System;
using System.Linq;
using Framework.Extensions;

namespace Framework.Sql
{
    public class UpdateSqlBuilder : InsertSqlBuilder
    {
        private readonly string _idColumnName;
        private readonly int _id;

        public UpdateSqlBuilder(string connectionString, string tableName, string idColumnName, int id) : base(connectionString, tableName)
        {
            _idColumnName = idColumnName;
            _id = id;
        }

        public override int ExecuteSql()
        {
            var sql = string.Format("update {0} set {1} where {2} = {3}",
                                    TableName,
                                    ColumnNames.Select(columnName => string.Format("[{0}] = @{0}", columnName)).SeparateBy(", "),
                                    _idColumnName,
                                    _id);

            return ColumnNames
                .Select((s, i) => new {Name = s, Index = i})
                .Aggregate(new SqlExecutor(ConnectionString).WithCommand(sql),
                           (adder, a) => adder.AddParameter(a.Name, ColumnValues[a.Index] ?? DBNull.Value))
                .Exec();
        }
    }
}